package com.oocl.hw1.task3.controller.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.oocl.hw1.task1.utils.RegularExpressionUtil;
import com.oocl.hw1.task1.utils.RegularExpressionUtil.Regular;
import com.oocl.hw1.task3.controller.PatchDataProcessable;
import com.oocl.hw1.task3.pojo.Customer;

public class CustomerProcessor implements PatchDataProcessable<Customer>{

	private DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
	
	@Override
	public Customer stringToObject(String[] str) {
		if(str== null || str.length<5)
			return null;
		
		String id = str[0];
		String name = str[1];
		String email = str[2];
		String sex = str[3];
		String birthday = str[4];
		
		if(!RegularExpressionUtil.match(Regular.NUMBERS, id))
			return null;
		if(!RegularExpressionUtil.match(Regular.NAME, name))
			return null;
		if(!RegularExpressionUtil.match(Regular.EMAIL, email))
			return null;
		if(!RegularExpressionUtil.match(Regular.SEX, sex))
			return null;
		if(!RegularExpressionUtil.match(Regular.BIRTHDAY, birthday))
			return null;
		
		Customer customer = new Customer();
		customer.setId(Integer.valueOf(id));
		customer.setName(name);
		customer.setEmail(email);
		customer.setSex((sex.length()==4)?true:false);//true:男
		try {
			customer.setBirthday(dateFormat.parse(birthday));
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return customer;
	}

	@Override
	public String[] objectToString(Customer obj) {
		String[] values = new String[5];
		values[0] = obj.getId()+"";
		values[1] = obj.getName();
		values[2] = obj.getEmail();
		values[3] = (obj.isSex())?"male":"female";
		values[4] = dateFormat.format(obj.getBirthday());
		return values;
	}

}
